package com.hebeu.group.controller;

import com.hebeu.group.pojo.User;
import com.hebeu.group.service.UserService;
import com.hebeu.group.util.JSONResult;
import com.hebeu.group.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 言立慧
 * @date 2018/12/20 15:22
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/login.action")
    @ResponseBody
    public User login(String userName, String userPwd, HttpSession session) {
        List<User> users = userService.selectUser(userName, userPwd);
        // 判断查询到的用户数量是否为0
        if (users.size() < 1) {
            return null;
        } else {
            // 将用户存入session
            session.setAttribute("user", users.get(0));
            // 不为0则返回
            return users.get(0);
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/logout.action")
    public void logout() {
        return;
    }

    /**
     * 修改密码
     *
     * @param newPassword
     * @param session
     * @return
     */
    @RequestMapping("/alterPassword")
    public JSONResult alterPassword(String newPassword, HttpSession session) {
        // 1. 获取用户
        User user = (User) session.getAttribute("user");
        user.setUserPassword(newPassword);
        // 2. 修改密码
        userService.updateUser(user);
        // 3. 返回数据
        return JSONResult.ok();
    }

    /**
     * 查询用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/catUserInfo")
    @ResponseBody
    public JSONResult catUserInfo(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return JSONResult.ok(user);
    }
}
